/*
** my_cd.c for  in /home/gomes_m//my-project-a-moi/client
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Wed Jul 31 00:49:13 2013 mickael gomes
** Last update Wed Jul 31 01:05:27 2013 mickael gomes
*/

#include		<stdio.h>
#include		<stdlib.h>
#include		<unistd.h>
#include		"struct.h"
#include		"prototypes.h"

void			go_to_current_dir(char *path)
{
  if ((chdir(path) == -1))
    my_putstr(2, "Chdir has failed.\n", 0);
}

char			*get_previous_dir(t_cmd *cmd)
{
  char			*actual_path;
  int			i = 0;
  int			pos = 0;

  actual_path = xmalloc(1024 * sizeof(char));
  if ((actual_path = getcwd(actual_path, 1024)) == NULL)
      my_putstr(2, "Getcwd is failed.\n", 0);
  if (!my_strcmp(cmd->home, actual_path))
    return (cmd->home);
  else
    {
      while (actual_path[i])
	{
	  if (actual_path[i] == '/' && actual_path[i + 1] != 0)
	    pos = i;
	  i++;
	}
      actual_path[pos + 1] = 0;
      return (actual_path);
    }
}

char			*check_arg(char *path, t_cmd *cmd)
{
  if (path == NULL || !my_strcmp(path, cmd->home))
    return (cmd->home);
  if (!my_strcmp(path, ".."))
    return (get_previous_dir(cmd));
  if (my_strncmp(path, cmd->home, my_strlen(cmd->home)))
    return (NULL);
  return (path);
}

void			my_cd(t_cmd *cmd, t_socket *socket)
{
  (void)socket;
  cmd->arguments = check_arg(cmd->arguments, cmd);
  printf("Je passe dans cd [%s]\n", cmd->arguments);
  if ((chdir(cmd->arguments) == -1))
    my_putstr(2, "Wrong path.\n", 0);
}
